package com.semidata.trp.business.report;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.ibatis.session.SqlSession;

import com.semidata.rtd.core.log.Logger;
import com.semidata.trp.business.mapper.BusinessMapper;
import com.semidata.trp.business.model.KeyWordModel;
import com.semidata.trp.business.utils.SessionUtils;

public class KeyWordData {
	private SqlSession session;
	public KeyWordData() {
		session = SessionUtils.getSession();
	}

	public List<KeyWordModel> loadKeyWordByLevel(Integer level, Integer parentId) {
		List<KeyWordModel> list = null;
        BusinessMapper mapper = session.getMapper(BusinessMapper.class);
        list = mapper.getKeywordsByLevel(level, parentId);
        if (list == null)
        	return new ArrayList<KeyWordModel>();
        else
        	return list;
	}
	
	public void insertKeyWord(KeyWordModel key) {
		try {
			BusinessMapper mapper = session.getMapper(BusinessMapper.class);
			mapper.insertKeyWord(key);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
            session.rollback();
		}
		
	}
	
	public void updateKeyWord(KeyWordModel key) {
		try {
			Timestamp lastUpdateTime = key.getLastUpdate();
			Timestamp currentTime = new Timestamp(System.currentTimeMillis());
			if (currentTime.getDay() != lastUpdateTime.getDay()) {
				BusinessMapper mapper = session.getMapper(BusinessMapper.class);
				mapper.updateKeyWord(key.getId());
				session.commit();
				key.setLastUpdate(currentTime);
			}
		} catch (Exception e) {
			e.printStackTrace();
            session.rollback();
		}
		
	}
	
	public void getKeywords(Map<String,KeyWordModel> key1, Map<String,Map<String,KeyWordModel>> key2, Map<Integer,Map<String,KeyWordModel>> key3) {

    	List<KeyWordModel> oneLevelKeys = loadKeyWordByLevel(1, null);
    	for (KeyWordModel k1 : oneLevelKeys) {
    		key1.put(k1.getKey(), k1);
    		List<KeyWordModel> towLevelKeys = loadKeyWordByLevel(2, k1.getId());
    		Map<String,KeyWordModel> keys2 = new HashMap<>();
    		key2.put(k1.getKey(), keys2);
    		for (KeyWordModel k2 : towLevelKeys) {
    			keys2.put(k2.getKey(), k2);
    			Map<String,KeyWordModel> keys3 = new HashMap<>();
    			key3.put(k2.getId(), keys3);
    			List<KeyWordModel> threeLevelKeys = loadKeyWordByLevel(3, k2.getId());
    			for(KeyWordModel k3 : threeLevelKeys) {
    				keys3.put(k3.getKey(), k3);
    			}
    		}
    	}
    }
    
    public void showdata(Map<String,KeyWordModel> key1, Map<String,Map<String,KeyWordModel>> key2, Map<Integer,Map<String,KeyWordModel>> key3) {
    	for (Map.Entry<String, KeyWordModel> m : key1.entrySet()) {
    		System.out.println("key 1 : " + m.getKey());
    		for (Map.Entry<String, KeyWordModel> m2 : key2.get(m.getKey()).entrySet()) {
    			System.out.println("key 2 : " + m2.getKey());
    			for (Map.Entry<String, KeyWordModel> m3 : key3.get(m2.getValue().getId()).entrySet()) {
    				System.out.println("key 3 : " + m3.getKey());
    			}
    		}
    	}
    	Logger.log("INFO", "get keys from mysql database : key1 size : " + key1.size() + " key2 size : " + key2.size() + " key3 size : " + key3.size());
    }
    public void checkAndAddKey(Map<String,KeyWordModel> key1, Map<String,Map<String,KeyWordModel>> key2, Map<Integer,Map<String,KeyWordModel>> key3,Set<KeyWord> keys) throws Exception{
    	long start = System.currentTimeMillis();
    	try {
	    	for (KeyWord kw : keys) {
	    		if (kw.getKey1() == null || kw.getKey1().isEmpty())
	    			continue;
	        	if (!key1.containsKey(kw.getKey1())) {
	        		KeyWordModel model = new KeyWordModel();
	        		model.setKey(kw.getKey1());
	        		model.setLastUpdate(kw.getTime());
	        		model.setLevel(1);
	        		model.setParentId(null);
	        		insertKeyWord(model);
	        		key1.put(kw.getKey1(), model);
	        		if (kw.getKey2() != null && !kw.getKey2().isEmpty()) {
		        		KeyWordModel model2 = new KeyWordModel();
		        		model2.setLastUpdate(kw.getTime());
		        		model2.setKey(kw.getKey2());
		        		model2.setLevel(2);
		        		model2.setParentId(model.getId());
		        		insertKeyWord(model2);
		        		Map<String,KeyWordModel> keys2 = new HashMap<>();
		        		keys2.put(kw.getKey2(), model2);
		        		key2.put(kw.getKey1(), keys2);
		        		if (kw.getKey3() != null && !kw.getKey3().isEmpty()) {
			        		KeyWordModel model3 = new KeyWordModel();
			        		model3.setKey(kw.getKey3());
			        		model3.setLastUpdate(kw.getTime());
			        		model3.setLevel(3);
			        		model3.setParentId(model2.getId());
			        		insertKeyWord(model3);
			        		Map<String,KeyWordModel> keys3 = new HashMap<>();
			        		keys3.put(kw.getKey3(), model3);
			        		key3.put(model2.getId(), keys3);
			        		Logger.log("INFO", "add a key words : " + model.getKey() + "-" + model2.getKey() + "-" + model3.getKey());
		        		} else {
		        			key3.put(model2.getId(), new HashMap<String,KeyWordModel>());
		        		}
	        		} else {
	        			key2.put(kw.getKey1(), new HashMap<String,KeyWordModel>());
	        		}
	        		
	        	} else {
	        		KeyWordModel ke1 = key1.get(kw.getKey1());
        			updateKeyWord(ke1);
	        		if (kw.getKey2() == null || kw.getKey2().isEmpty())
	        			continue;
	        		if (!key2.get(kw.getKey1()).containsKey(kw.getKey2())) {
	        			KeyWordModel k1 = key1.get(kw.getKey1());
	        			KeyWordModel model2 = new KeyWordModel();
	            		model2.setLastUpdate(kw.getTime());
	            		model2.setKey(kw.getKey2());
	            		model2.setLevel(2);
	            		model2.setParentId(k1.getId());
	            		insertKeyWord(model2);
	            		Map<String,KeyWordModel> keys2 = key2.get(kw.getKey1());
	            		keys2.put(kw.getKey2(), model2);
	            		if (kw.getKey3() != null && !kw.getKey3().isEmpty()) {
		            		KeyWordModel model3 = new KeyWordModel();
		            		model3.setKey(kw.getKey3());
		            		model3.setLastUpdate(kw.getTime());
		            		model3.setLevel(3);
		            		model3.setParentId(model2.getId());
		            		insertKeyWord(model3);
		            		Map<String,KeyWordModel> keys3 = new HashMap<>();
		            		keys3.put(kw.getKey3(), model3);
		            		key3.put(model2.getId(), keys3);
		            		Logger.log("INFO", "add a key words : " + ke1.getKey() + "-" + model2.getKey() + "-" + model3.getKey());
	            		} else {
	            			key3.put(model2.getId(), new HashMap<String,KeyWordModel>());
	            		}
	        			
	        		} else {
                        KeyWordModel ke2 = key2.get(kw.getKey1()).get(kw.getKey2());
	        			updateKeyWord(ke2);
	        			if (kw.getKey3() == null || kw.getKey3().isEmpty())
	        				continue;
	        			KeyWordModel k2 = key2.get(kw.getKey1()).get(kw.getKey2());
	        			if (!key3.get(k2.getId()).containsKey(kw.getKey3())) {
	            			KeyWordModel model3 = new KeyWordModel();
	                		model3.setKey(kw.getKey3());
	                		model3.setLastUpdate(kw.getTime());
	                		model3.setLevel(3);
	                		model3.setParentId(k2.getId());
	                		insertKeyWord(model3);
	                		Map<String,KeyWordModel> keys3 = key3.get(k2.getId());
	                		keys3.put(kw.getKey3(), model3);
	                		Logger.log("INFO", "add a key words : " + ke1.getKey() + "-" + ke2.getKey() + "-" + model3.getKey());
	        			} else {
	        				KeyWordModel k3 = key3.get(k2.getId()).get(kw.getKey3());
	        				updateKeyWord(k3);
	        			}
	        			
	        		}
	        	}
	        }
    	}catch (Exception e) {
    		e.printStackTrace();
    		Logger.log("ERROR", "write key word fail");
    		Logger.log("ERROR", e);
    	}
    	long end = System.currentTimeMillis();
    	Logger.log("INFO", "cost time in insert a keyword : " + (end - start));
    }

	/*public static void main(String[] args) throws Exception {
		SqlSession session = SessionUtils.getSession();
		KeyWordData kwd = new KeyWordData();
		kwd.getKeywords();
		kwd.showdata();
		Set<KeyWord> kws = new HashSet<>();
		KeyWord kw1 = new KeyWord();
		kw1.setKey1("key6");
		kw1.setKey2("key61");
		kw1.setKey3("key611");
		kw1.setTime(new Timestamp(System.currentTimeMillis()));
		KeyWord kw2 = new KeyWord();
		kw2.setKey1("key7");
		kw2.setKey2("key71");
		kw2.setKey3("key711");
		kw2.setTime(new Timestamp(System.currentTimeMillis()));
		KeyWord kw3 = new KeyWord();
		kw3.setKey1("key6");
		kw3.setKey2("key62");
		kw3.setKey3("key621");
		kw3.setTime(new Timestamp(System.currentTimeMillis()));
		KeyWord kw4 = new KeyWord();
		kw4.setKey1("key5");
		kw4.setKey2("key52");
		kw4.setKey3("key529");
		kw4.setTime(new Timestamp(System.currentTimeMillis()));
		kws.add(kw1);
		kws.add(kw2);
		kws.add(kw3);
		kws.add(kw4);
		kwd.checkAndAddKey(kws);
		/*KeyWordModel kwm = new KeyWordModel();
		KeyWordData kwd = new KeyWordData();
		List<KeyWordModel> list = kwd.loadKeyWordByLevel(session, 1, null);
		for (KeyWordModel k : list) {
			System.out.println("" + k.getParentId());
			
		}
		kwm.setKey("衣服");
		kwm.setLastUpdate(new Timestamp(System.currentTimeMillis()));
		kwm.setLevel(1);
		kwm.setParentId(null);
		kwd.insertKeyWord(session, kwm);
		System.out.println("id : " + kwm.getId());
		session = SessionUtils.getSession();
		kwd.updateKeyWord(session, 1);
	}*/
	
}
